import * as THREE from './three.module.js';
import { Line2 } from './Line2.js';
import { LineMaterial } from './LineMaterial.js';
import { LineGeometry } from './LineGeometry.js';

const linetype = 0;//0=normal 1=fat
mapboxgl.accessToken = 'pk.eyJ1IjoiaG91eGlleXUiLCJhIjoiY2pldjE5amU3NndzeDM5bzd5bm9ncDgycyJ9.j1F-Lgid3L5k2Abm8_xTeQ';
var map = (window.map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10',
    zoom: 18,
    center: [116.582, 35.415],
    pitch: 60,
    antialias: true // create the gl context with MSAA antialiasing, so custom layers are antialiased
}));

// var THREE = window.THREE;
function drawLine(points) {
    var mts = [ new THREE.LineBasicMaterial({
        vertexColors: true
    }),new LineMaterial({
        linewidth: 0.005, // in pixels
        vertexColors: true//THREE.VertexColors,
    }),]
    var material = mts[linetype]
    var geos = [new THREE.Geometry(),
        new LineGeometry()
    ]
    var geometry = geos[linetype]

    var positions = [];
    var colors = [];

    points.forEach((d, i) => {
        const { x, y, z } = d;
        var c=new THREE.Color(i ? i : 1, i?0:1, i ? 0 : 1);
        if (linetype == 0) {
            geometry.vertices.push(new THREE.Vector3(x, y, z));
            // geometry.colors.push( new THREE.Color('rgb('+(i==1?0:255)+',0,'+(i==0?0:255)+')'))
            geometry.colors.push(c)
        }
        else {
            positions.push(x, y, z);
            colors.push(c.r, c.g, c.b)
        }

    });
    if (linetype == 1) {
        geometry.setPositions(positions);
        geometry.setColors(colors);
    }
    // console.log(colors,geometry.colors)
    var linegeo=[
        new THREE.Line(geometry, material),
        new Line2(geometry, material)
    ]
    return linegeo[linetype];
}
$.ajaxSettings.async = false;
var linesdata;
// $.getJSON(encodeURI('http://124.133.27.90:6082/main/getGEOJsonByFilter'),
//     {
//         filter: "1=1",//"对象类型='一套表单位'" ,
//         fields:'名称,对象类型,经度,纬度',
//         limit: 100
//     },
$.getJSON('jp4data.json',
    function (res) {
        linesdata = res;
    });
// configuration of the custom layer for a 3D model per the CustomLayerInterface
var lineGroup;
var customLayer = {
    id: '3d-model',
    type: 'custom',
    renderingMode: '3d',
    onAdd: function (map, gl) {
        this.camera = new THREE.Camera();
        this.scene = new THREE.Scene();
        // create two three.js lights to illuminate the model
        var directionalLight = new THREE.DirectionalLight(0xffffff);
        directionalLight.position.set(0, -70, 100).normalize();
        this.scene.add(directionalLight);

        var directionalLight2 = new THREE.DirectionalLight(0xffffff);
        directionalLight2.position.set(0, 70, 100).normalize();
        this.scene.add(directionalLight2);
        this.map = map;
        lineGroup = new THREE.Group();

        linesdata.features.forEach(function (element, inx) {
            if (element.geometry.coordinates[0] == null) return;
            var basept = mapboxgl.MercatorCoordinate.fromLngLat(
                element.geometry.coordinates,
                0
            );
            var toppt = mapboxgl.MercatorCoordinate.fromLngLat(
                element.geometry.coordinates,
                500
            );

            var lineMesh = drawLine([basept, toppt]);
            lineMesh.scale.set(1,1,Math.random()*2);
            lineGroup.add(lineMesh);
        });
        this.scene.add(lineGroup);
        // var geometry = new THREE.BoxGeometry( 10, 10, 10 );
        // var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
        // var cube = new THREE.Mesh( geometry, material );
        // this.scene.add( cube );
        // use the Mapbox GL JS map canvas for three.js
        this.renderer = new THREE.WebGLRenderer({
            canvas: map.getCanvas(),
            context: gl,
            antialias: true
        });

        this.renderer.autoClear = false;
    },
    render: function (gl, matrix) {
        // lineGroup.scale.add(new THREE.Vector3(0,0,0.1))
        // if(lineGroup.scale.z > 2){
        //     lineGroup.scale.setZ(0)
        // }
        lineGroup.children.forEach(function(obj){
            obj.scale.add(new THREE.Vector3(0,0,0.1))
            if(obj.scale.z > 2){
                obj.scale.setZ(0.1)
            }
        //     // obj.material.color = new THREE.Color(Math.random(),Math.random(),Math.random());
        //     obj.rotation.x += 0.01;
        //     obj.rotation.y += 0.01;
        })

        var m = new THREE.Matrix4().fromArray(matrix);
        var l = new THREE.Matrix4()
        this.camera.projectionMatrix = m.multiply(l);
        // console.log(this.renderer)
        this.renderer.state.reset();
        this.renderer.render(this.scene, this.camera);
        this.map.triggerRepaint();
    }
};

map.on('style.load', function () {
    map.addLayer(customLayer, 'waterway-label');
});